package com.yonyou.base.common.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * @author wolf
 * @date 2020/10/20
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    private static final MessageResult SYS_ERROR = new MessageResult(MessageResult.STATUS_ERROR, "system is busy, try again later.");

    private static final MessageResult PARAM_ERROR = new MessageResult(MessageResult.STATUS_ERROR, "Incoming parameters values are not legal.");

    /**
     * 运行时异常
     *
     * @param ex ex
     */
    @ExceptionHandler(RuntimeException.class)
    public MessageResult runtimeExceptionHandler(RuntimeException ex) {
        logger.error("运行时异常", ex);
        return SYS_ERROR;
    }

    /**
     * 空指针
     *
     * @param ex ex
     */
    @ExceptionHandler(NullPointerException.class)
    public MessageResult nullPointerExceptionHandler(NullPointerException ex) {
        logger.error("空指针", ex);
        return SYS_ERROR;
    }

    @ExceptionHandler({MissingServletRequestParameterException.class, MissingServletRequestPartException.class})
    public MessageResult missParameterExceptionHandler(MissingServletRequestParameterException ex) {
        logger.error("入参不足", ex);
        return PARAM_ERROR;
    }

    /**
     * 400 类型转换异常
     *
     * @param ex ex
     */
    @ExceptionHandler({TypeMismatchException.class})
    public MessageResult requestTypeMismatch(TypeMismatchException ex) {
        logger.debug("参数类型转换错误", ex);
        return PARAM_ERROR;
    }

    /**
     * 500错误
     *
     * @param ex ex
     */
    @ExceptionHandler({ConversionNotSupportedException.class,
            HttpMessageNotWritableException.class})
    public MessageResult server500(RuntimeException ex) {
        logger.error("服务器异常", ex);
        return SYS_ERROR;
    }

    /**
     * 堆栈异常
     *
     * @param ex ex
     */
    @ExceptionHandler({StackOverflowError.class})
    public MessageResult requestStackOverflow(StackOverflowError ex) {
        logger.error("堆栈异常", ex);
        return SYS_ERROR;
    }

    /**
     * 其他
     *
     * @param ex ex
     */
    @ExceptionHandler({Exception.class})
    public MessageResult exception(Exception ex) {
        logger.error("其他异常", ex);
        return SYS_ERROR;
    }

}
